package com.steven.nio.ZeroCopy;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class CopyServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(4332));
        FileOutputStream fileOutputStream = new FileOutputStream("D:/ca.rar");
        FileChannel fileChannel = fileOutputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(4096);
        int readCount = 0;
        int len = 0;
        while (true){
            SocketChannel socketChannel = serverSocketChannel.accept();
            socketChannel.configureBlocking(true);
            while ((len = socketChannel.read(byteBuffer)) != -1) {
                readCount += len;
                if (len != 0) {
                    byteBuffer.flip();
                    int write = fileChannel.write(byteBuffer);
                    System.out.println("总共读取：" + write);
                }
                byteBuffer.clear();
            }
            fileChannel.close();
            System.out.println("总共读取：" + readCount);

        }

    }
}
